<?php

namespace App\Traits;


use App\Models\MerchantStore;
use App\Models\Store;
use App\Services\PrintSqlService;
use Illuminate\Http\Request;

trait  ResponseTrait
{
    public function successResponse(string $msg, $data = []): string
    {
        if (is_array($data)) {
            return json_encode(array_merge([
                'status' => 1,
                'message' => $msg,
            ], $data));
        } else {
            return json_encode([
                'status' => 1,
                'message' => $msg,
                "data" => $data
            ]);
        }
    }


    public function errorResponse(string $msg): string
    {
        return json_encode([
            'status' => 2,
            'message' => $msg
        ]);
    }


    protected function getMerchantWhere(Request $request, int $merchant_id): array
    {

        //店铺条件
        $store_id = $request->get("store_id", "");
        //查询全部的门店
//            PrintSqlService::listen();
        $storeIds = MerchantStore::query()->where("merchant_id", $merchant_id)->where(function ($query) use ($store_id) {
            if (!empty($store_id)) {
                $query->where("store_id", $store_id);
            }
        })->pluck("store_id")->toArray();
        if (empty($storeIds)) {
            throw new \Exception("当前商户没有绑定店铺");
        }
        //查询总店,给查询条件设置pid  利用store_pid store_id 索引
        $store = Store::query()->select(["id", "store_id", "pid"])->whereIn("store_id", $storeIds)
            ->get()->toArray();
        //获取总店数据
        $storeParendId = [];
        foreach ($store as $v) {
            if ($v["pid"] == 0) {
                $storeParendId[] = $v["id"];
            } else {
                $storeParendId[] = $v["pid"];
            }
        }
        //查询总店
        $storeAll = Store::query()->whereIn("id", $storeParendId)->get();
        $storeP = null;
        foreach ($storeAll as $store) {
            if ($store->pid == 0) {
                $storeP = $store;
                break;
            }
        }
        if (empty($storeP) || $storeP->pid != 0) {
            throw new \Exception("总店不存在");
        }
        return [$storeP, $storeIds];
    }

}
